/*************************************************************************
	> File Name: common.c
	> Author: WangYiFei
	> Mail: 824537320@qq.com
	> Created Time: Sat 09 Jan 2021 02:04:21 PM CST
 ************************************************************************/

#include "head.h"

int make_nonblock(int fd) {
    int flag;
    if ((flag = fcntl(fd, F_GETFL)) < 0) {
        // perror("fcntl");
        return -1;
    }
    flag |= O_NONBLOCK;
    return fcntl(fd, F_SETFL, flag);
}

int make_block(int fd) {
    int flag;
    if ((flag = fcntl(fd, F_GETFL)) < 0) {
        // perror("fcntl");
        return -1;
    }
    flag &= ~O_NONBLOCK;
    return fcntl(fd, F_SETFL, flag);
}

int recv_str_nonblock(int sockfd, char *buff, long size, int timeout) {
    fd_set rfds;
    struct timeval tv;
    int retval;

    FD_ZERO(&rfds);
    FD_SET(sockfd, &rfds);

    tv.tv_sec = 0;
    tv.tv_usec = timeout;

    retval = select(sockfd + 1, &rfds, NULL, NULL, &tv);
    if (retval == -1) {
        // perror("select");
        return -1;
    } else if (retval) {
        if (recv(sockfd, buff, size, 0) <= 0) {
            // perror("recv");
            return -1;
        }
        return 0;
    } else {
        return -1;
    }
    return -1;
}
